from django.db import models
from settings import MEDIA_ROOT
from django.db.models import signals
import datetime
import settings


# Create your models here.
class Module(models.Model):
    Unknown = 0
    XibView = 10
    StoryView = 11
    AcivityView = 20
    CordovaView = 30
    WebView = 31
    
    MODULE_TYPE_CHOICES = (
        (Unknown, 'Unknown'),
        (XibView, 'iOS - XibView'),
        (StoryView, 'iOS - StoryView'),
        (XibView, 'Android - ActiveView'),
        (CordovaView, 'Html5 - CordovaView'),
        (WebView, 'Html5 - WebView')
    )
    
    MODULE_PLATFORM_CHOICES = (
                               ("All", "All"),
                               ("iOS", "iOS"),
                               ("Android", "Android")
                               )
    platform = models.CharField(max_length=10, choices=MODULE_PLATFORM_CHOICES, default="All")
    mid = models.IntegerField()
    name = models.CharField(max_length=100)
    
    position = models.PositiveIntegerField(blank=False, null=False)
    type = models.SmallIntegerField(choices=MODULE_TYPE_CHOICES,default=Unknown)
    enabled = models.BooleanField(default=False)
    lastest_version = models.CharField(max_length=10, default="0.0.0")
    lastest_updated = models.DateTimeField(default=datetime.datetime(1970, 1, 1, 0, 0, 0))
    

    def __unicode__(self):
        return "%s [%s] %s" % (self.pk, self.platform, self.name)
    
    def icon(self):
        return "%s/modules/icon_%d@2x.png" % (settings.MEDIA_URL, self.id)
    
    class Meta(object):
        ordering = ('position',)

    
class Version(models.Model):
    version = models.CharField(max_length=10)
    alias = models.CharField(max_length=10)
    comment = models.TextField()
    updated = models.DateTimeField()
    file = models.FileField(upload_to='module/version')
    module = models.ForeignKey('Module')

def update_module_version(sender, instance, created, **kwargs):
    module = instance.module
    if instance.version > module.lastest_version:
        module.lastest_version = instance.version
        module.save()

signals.post_save.connect(update_module_version, sender=Version)

    
